package com.ruoyi.teaching.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.teaching.domain.YaStudent;
import com.ruoyi.teaching.dto.AttendanceDTO;
import com.ruoyi.teaching.mapper.YaStudentMapper;
import com.ruoyi.teaching.mapper.YaTeachingPlanMapper;
import com.ruoyi.teaching.vo.AttendanceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.teaching.mapper.YaAttendanceMapper;
import com.ruoyi.teaching.domain.YaAttendance;
import com.ruoyi.teaching.service.IYaAttendanceService;

/**
 * 考勤汇总Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-31
 */
@Service
public class YaAttendanceServiceImpl implements IYaAttendanceService
{
    @Autowired
    private YaAttendanceMapper yaAttendanceMapper;
    @Autowired
    private YaStudentMapper yaStudentMapper;

    /**
     * 查询考勤汇总
     *
     * @param id 考勤汇总主键
     * @return 考勤汇总
     */
    @Override
    public YaAttendance selectYaAttendanceById(Long id)
    {
        return yaAttendanceMapper.selectYaAttendanceById(id);
    }

    /**
     * 查询考勤汇总列表
     *
     * @param yaAttendance 考勤汇总
     * @return 考勤汇总
     */
    @Override
    public List<YaAttendance> selectYaAttendanceList(YaAttendance yaAttendance)
    {
        return yaAttendanceMapper.selectYaAttendanceList(yaAttendance);
    }

    /**
     * 新增考勤汇总
     *
     * @param yaAttendance 考勤汇总
     * @return 结果
     */
    @Override
    public int insertYaAttendance(YaAttendance yaAttendance)
    {
        return yaAttendanceMapper.insertYaAttendance(yaAttendance);
    }

    /**
     * 修改考勤汇总
     *
     * @param yaAttendance 考勤汇总
     * @return 结果
     */
    @Override
    public int updateYaAttendance(YaAttendance yaAttendance)
    {
        return yaAttendanceMapper.updateYaAttendance(yaAttendance);
    }

    /**
     * 批量删除考勤汇总
     *
     * @param ids 需要删除的考勤汇总主键
     * @return 结果
     */
    @Override
    public int deleteYaAttendanceByIds(Long[] ids)
    {
        return yaAttendanceMapper.deleteYaAttendanceByIds(ids);
    }

    /**
     * 删除考勤汇总信息
     *
     * @param id 考勤汇总主键
     * @return 结果
     */
    @Override
    public int deleteYaAttendanceById(Long id)
    {
        return yaAttendanceMapper.deleteYaAttendanceById(id);
    }

    /**
     * 批量更新学生考勤信息
     *
     * @param attendanceList 学生考勤列表
     * @return 结果
     */
    @Override
    public int updateBatchAttendance(List<YaAttendance> attendanceList)
    {
        int successCount = 0;
        for (YaAttendance attendance : attendanceList)
        {
            /*// 根据学生姓名、日期和班级查询考勤记录
            YaAttendance existAttendance = yaAttendanceMapper.selectAttendanceByStudentAndDate(
                    attendance.getStudentName(), attendance.getDate(), attendance.getClassName());*/
            YaAttendance existAttendance = yaAttendanceMapper.selectOne(
                    new LambdaQueryWrapper<YaAttendance>()
                            .eq(YaAttendance::getClassName,attendance.getClassName())
                            .eq(YaAttendance::getDate,attendance.getDate())
                            .eq(YaAttendance::getStudentName,attendance.getStudentName())
            );


            if (existAttendance != null)
            {
                // 更新已有记录
                attendance.setId(existAttendance.getId());
                successCount += yaAttendanceMapper.updateYaAttendance(attendance);
            }
            else
            {
                // 插入新记录
                successCount += yaAttendanceMapper.insertYaAttendance(attendance);
            }
        }
        return successCount;
    }

    @Override
    public List<AttendanceDTO> selectYaAttendanceListByClassName(Date date) {
        List<AttendanceDTO> result = new ArrayList<>(100);
        AttendanceDTO attendanceDTO = new AttendanceDTO();
        //获取当前的系统用户名
        String username = SecurityUtils.getUsername();
        //根据username获取到studentName
        YaStudent yaStudent = yaStudentMapper.selectOne(
                new LambdaQueryWrapper<YaStudent>()
                        .eq(YaStudent::getUsername, username)
        );
        // 将Date转换为yyyy-MM格式的字符串，用于模糊查询
        String monthPattern = null;
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            monthPattern = sdf.format(date) + "%";
            String formattedDate = sdf.format(date);
            attendanceDTO.setDate(formattedDate);
        }
        else{
            //获取当前的时间
            Date currentDate = new Date();
            // 将Date转换为yyyy-MM格式的字符串，用于模糊查询
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            monthPattern = sdf.format(currentDate) + "%";
            String formattedDate = sdf.format(currentDate);
            attendanceDTO.setDate(formattedDate);
        }
        //根据改时间查询到当月的所有的考勤信息
        List<YaAttendance> yaAttendances = yaAttendanceMapper.selectList(
                new LambdaQueryWrapper<YaAttendance>()
                        .like(YaAttendance::getDate,monthPattern)
                        .eq(YaAttendance::getStudentName, yaStudent.getName())
        );
        //遍历yaAttendances，将其中的early、noon、night的数据分别添加到集合earlyList、noonList、nightList中，类型是long类型
        List<Long> earlyList = new ArrayList<>(100);
        List<Long> noonList = new ArrayList<>(100);
        List<Long> nightList = new ArrayList<>(100);
        for (YaAttendance yaAttendance : yaAttendances) {
            earlyList.add(yaAttendance.getEarly());
            noonList.add(yaAttendance.getNoon());
            nightList.add(yaAttendance.getNight());
        }
        attendanceDTO.setEarlyList(earlyList);
        attendanceDTO.setNoonList(noonList);
        attendanceDTO.setNightList(nightList);
        //根据该月份的earlyList中的元素总个数获取到dayCount
        long dayCount = earlyList.size();
        attendanceDTO.setDayCount(dayCount);
        result.add(attendanceDTO);
        return result;
    }

    @Override
    public List<AttendanceVo> selectYaAttendanceStuOrAllListByDate(Date date) throws ParseException {
        List<AttendanceVo> result = new ArrayList<>(100);
        AttendanceVo attendanceVo = new AttendanceVo();
        //获取当前的系统用户名
        String username = SecurityUtils.getUsername();
        // 将Date转换为yyyy-MM格式的字符串，用于模糊查询
        String monthPattern = null;
        int dayCount = 0;
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            monthPattern = sdf.format(date) + "%";
            //判断该date月份总共有几天，用一个dayCount来记录
            //判断该date月有多少天
            // 使用Calendar获取月份的天数
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            // 获取当前月份的最后一天
            dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        else{
            //获取当前的时间
            Date currentDate = new Date();
            // 将Date转换为yyyy-MM格式的字符串，用于模糊查询
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            monthPattern = sdf.format(currentDate) + "%";
            //判断该date月份总共有几天，用一个dayCount来记录
            //判断该date月有多少天
            // 使用Calendar获取月份的天数
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            // 获取当前月份的最后一天
            dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        attendanceVo.setDayCount(dayCount);
        YaStudent isStudent = yaStudentMapper.selectOne(
                new LambdaQueryWrapper<YaStudent>()
                        .eq(YaStudent::getUsername,username)
        );
        if (isStudent != null) {
            //学生端
            //根据username获取到studentName
            YaStudent yaStudent = yaStudentMapper.selectOne(
                    new LambdaQueryWrapper<YaStudent>()
                            .eq(YaStudent::getUsername, username)
            );
            List<YaAttendance> attendanceList = yaAttendanceMapper.selectList(
                    new LambdaQueryWrapper<YaAttendance>()
                            .like(YaAttendance::getDate,monthPattern)
                            .eq(YaAttendance::getStudentName,yaStudent.getName())
            );
            attendanceVo.setYaAttendanceList(attendanceList);
            List<YaStudent> studentList = yaStudentMapper.selectList(
                    new LambdaQueryWrapper<YaStudent>()
                            .eq(YaStudent::getUsername,username)
            );
            attendanceVo.setStudentList(studentList);
        }
        else {
            //老师端
            List<YaAttendance> attendanceList = yaAttendanceMapper.selectList(
                    new LambdaQueryWrapper<YaAttendance>()
                            .like(YaAttendance::getDate,monthPattern)
            );
            attendanceVo.setYaAttendanceList(attendanceList);
            List<YaStudent> studentList = yaStudentMapper.selectList(
                    new LambdaQueryWrapper<>()
            );
            attendanceVo.setStudentList(studentList);
        }
        result.add(attendanceVo);
        return result;
    }
}
